package fr.inria.arles.tempManagement.preferencesStore.query;

import java.sql.*;

import static fr.inria.arles.tempManagement.preferencesStore.query.Constants.*;

/**
 * An implementation of the Query interface using a database. Provides
 * implementation for executing queries over the database to its subclasses.
 * 
 * @@author ajay chhatwal
 */
public abstract class AbstractQuery implements Query {

    /**
     * Execute specified SQL query on the database
     * 
     * @param sql
     *            the SQL query
     * @param parameters
     *            the parameters to the query
     * @return the ResultSet object corresponding to the query
     * @throws ClassNotFoundException
     *             if the Database Driver Class is missing
     * @throws SQLException
     *             if there is a problem in accessing the database
     */
    protected ResultSet executeQuery(String sql, String[] parameters)
            throws Exception {

        Class.forName(JDBC_DRIVER_CLASS);
        Connection con = DriverManager.getConnection(JDBC_URL, DB_USERNAME,
                DB_PASSWORD);

        PreparedStatement smnt = con.prepareStatement(sql);

        // Handle parameters
        for (int i = 0; i < parameters.length; i++) {
            // System.out.println(i + parameters[i]);
            smnt.setString(i + 1, parameters[i]);
        }

        System.out.println("SQL Query: " + smnt.toString());
        
        boolean hasResult;
        try {
            hasResult = smnt.execute();
        } catch (SQLException e) {
            throw new Exception("SQL Error");
        }
        if (hasResult) {
            return smnt.getResultSet();
        } else {
            int updatecount=smnt.getUpdateCount();
            if(updatecount<1)
                throw new Exception("Update Failed");
            return null;
        }
    }

    /**
     * Executes the query represented by this Query object.
     * 
     * @param args
     *            the arguments to this Query
     * @return The result of the query encoded into a string
     * @throws ClassNotFoundException
     *             if the Database Driver Class is missing
     * @throws SQLException
     *             if there is a problem in executing the query or the database
     */
    public abstract String execute(String[] args)
            throws Exception;
}
